<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Fin_co2buy extends Model
{
    public function getfin_co2buys($res)
    {
        $lang = $res['lang'];
        //处理发生的日期
        $dateday = getTimeDate(null, 7);
        $admindata = session('admin');
        $admin_id = $admindata['id'];
        if ($admindata['position_id'] != 1 && $admindata['position_id'] != 2) {
            //获取支付账号
            $whereacc[] = ["exp", "FIND_IN_SET($admin_id,admin_ids)"];
        }
        //付款账号
        $whereacc[] = ["exp", "FIND_IN_SET('2',is_payment)"];

        $whereacc['a.is_public'] = 1;//是否公开
        //支付账号
        $accountname = Db::name('accounts')->alias('a')->join('nt_banks b', 'a.banks_id=b.id', 'left')->field('a.id,a.bankname,a.account_num,a.is_main,b.name')->where($whereacc)->select();

        $yearmonth = getNextMonthDays($res['yearmonth']);//下一个月日期
        $startime = strtotime($yearmonth[0]);
        $lasttime = strtotime($yearmonth[1]);
        $arr = array();
        //获取付款的流水
        $mapwhere['a.happen_day'] = ['between', "$startime,$lasttime"];
        $data = Db::name('fin_co2buy')->alias('a')->join('nt_fin_co2buy_remarks b', 'b.fin_co2buy_id=a.id', 'left')->field('a.*,b.remarks')->where($mapwhere)->page($res['page'], $res['pageSize'])->select();

        foreach ($data as $datakey => $dataval) {
            $data[$datakey]['update_date'] = getTimeDate($dataval['update_at'], 12);//更新时间
            if ($lang != 'zh') {
                //发生日期
                $datehappen = $data[$datakey]['happen_date'] = getTimeDate($dataval['happen_day'], 8);
                if (in_array($datehappen, $arr)) {
                    $data[$datakey]['happen_date'] = '';
                }
                array_push($arr, $datehappen);
            } else {
                $data[$datakey]['happen_date'] = $datehappen = getTimeDate($dataval['happen_day'], 7);
                if (in_array($datehappen, $arr)) {
                    $data[$datakey]['happen_date'] = '';
                }
                array_push($arr, $datehappen);
            }
            //公司名
            $data[$datakey]['companyname'] =getValue('company',['id'=>$dataval['co_id']],'name');
            //编辑者
            $data[$datakey]['updatename'] = getValue('admin',['id'=>$dataval['update_id']],'nickname');
            //对公付款id 下的合同是否付清
            $proids = array_unique(array_column(getables('fin_co2buy_po', ['fin_co2buy_id' => $dataval['id']]), 'po_id'));
            $data[$datakey]['agreement'] = $this->getfinish($proids);
            $data[$datakey]['time'] = time();
        }

        $count = Db::name('fin_co2buy')->alias('a')->join('nt_fin_co2buy_remarks b', 'b.fin_co2buy_id=a.id', 'left')->where('a.happen_day', 'between', [$startime, $lasttime])->count();

        $resdatas = array(
            'happen_day' => $dateday,
            'data' => $data,
            'size' => $count,
            'accountins' => $accountname,
        );
        return $resdatas;
    }

    public function getfinish($proids)
    {
        $finstatus = '';
        foreach ($proids as $proidskey => $proidsval) {
            $finishday = getinfo($proidsval, 'buy_po')['finish_day'];
            $code = numzero($proidsval);
            if ($finishday == 0) {
                //表示没有付清
                $finstatus .= "<span class='orange'>$code</span>" . '/';
            } else {
                $finstatus .= "<span class='black'>$code</span>" . '/';
            }
        }
        return rtrim($finstatus, '/');
    }


    //付款登记的添加与编辑
    public function cotwobuyaddedit($data)
    {
        $ckdata = notEmpty(['account_id' => lang("payment_account"), 'co_id' => lang("company"), 'bank_id' => lang("company_account")]);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        //付款的合同数据
        if (!isset($data['agreement'])) {
            return array('msg' => lang("please_select_the_contract_to_be_paid"), 'status' => 3);
        }
        //付款登记时间
        $finupdata['happen_day'] = $findatas['happen_day'] = $updata['happen_day'] = $data['happen_day'] = strtotime($data['happen_day']);
        $findatas['create_at'] = $findatas['update_at'] = $updata['update_at'] = $data['create_at'] = $data['update_at'] = time();
        $findatas['create_id'] = $findatas['update_id'] = $updata['update_id'] = $data['create_id'] = $data['update_id'] = session('userid');
        $data['is_pay'] = 1;//付款标志
        $money = array();
        $count = array();
        //统计合同的具体的付款金额
        foreach ($data['agreement'] as $keys => $vals) {
            //采购费用
            if (isset($vals['paypoarr'])) {
                $agreeone = $vals['paypoarr'];
                foreach ($agreeone as $agreeonekey => $agreeoneval) {
                    //勾选的合同编号
                    if ($agreeoneval['check'] == 'true') {
                        array_push($count, $agreeoneval['price']);
                        //付款金额不能小于0
                        if ($agreeoneval['price'] <= 0) {
                            return array('msg' => lang("payment_amount_can't_be_less_than_or_equal_to_0"), 'status' => 0);
                            exit;
                        }
                        //付款金额不能大于应付金额 针对每一个合同的
                        if ($agreeoneval['price'] > $agreeoneval['amount']) {
                            return array('msg' => lang("the_payment_amount_can't_be_greater_than_the_amount_payable,_contract_number:") . $agreeoneval['po_id'], 'status' => 0);
                            exit;
                        }
                        $money[] = array('po_id' => $agreeoneval['po_id'], 'amount' => $agreeoneval['price'], 'buy_po_payId' => $agreeoneval['id']);
                    }
                }
            } else {
                return array('msg' => lang("please_select_the_contract_to_be_paid"), 'status' => 3);
            }
        }
        if (empty($count)) {
            return array('msg' => lang("please_select_the_contract_to_be_paid"), 'status' => 3);
        }

        $summoney = array_sum(array_column($money, 'amount'));
        //付款的合同金额与总应付的金额不等
        if ($summoney != $data['amount']) {
            return array('msg' => lang("payment_amount_isn't_equal_to_contract_value"), 'status' => 0);
        }
        // fin_co2buy_id 流水ID
        $fin_co2buy_id = isset($data['id']) ? $data['id'] : 0;
        //更新合同信息
        $res_buy = model('Buy')->buyPoPayAction($data['agreement'], $fin_co2buy_id);

        $finupdata['co_id'] = $findatas['co_id'] = $data['co_id'];
        $findatas['type'] = 2;//实付
        $findatas['top'] = 0;
        $finupdata['amount'] = $findatas['amount'] = $data['amount'];//实付金额
        $findatas['table_name'] = 'fin_co2buy';//表名
        if ($data['act'] == 'cotwobuyadd') {
            unset($data['agreement']);
            Db::startTrans();
            $fin_co2buy_id = $this->strict(false)->insertGetId($data);//对公收付款登记表

            $findata['fin_co2buy_id'] = $fin_co2buy_id;
            $findata['remarks'] = $data['remarks'];
            Db::name('fin_co2buy_remarks')->insert($findata);//财务流水备注
            //合同表的写入
            array_walk($money, function (&$v, $k, $p) {
                $v = array_merge($v, $p);
            }, array('fin_co2buy_id' => $fin_co2buy_id));
            //采购合同付款登记
            $finids = $this->setfinco($money, $fin_co2buy_id);
            $findatas['record_id'] = $fin_co2buy_id;//记录id
            $fin_id = Db::name('fin_co')->insertGetId($findatas);//公司流水表id

            $insertata['fin_co_id'] = $fin_id;
            $insertata['remarks'] = $data['remarks'];
            Db::name('fin_co_remarks')->insertGetId($insertata);//公司流水备注表
            if ($fin_co2buy_id && $finids && $fin_id) {
                Db::commit();
                return array('msg' => lang("added_successfully"), 'status' => 1);
            } else {
                return array('msg' => lang("add_failed"), 'status' => 0);
            }
        } elseif ($data['act'] == 'cotwobuyedit') {
            Db::startTrans();
            $updata['account_id'] = $data['account_id'];
            $updata['co_id'] = $data['co_id'];
            $updata['bank_id'] = $data['bank_id'];
            $updata['amount'] = $data['amount'];
            $cotwoedit = $this->where('id', $data['id'])->update($updata);//更新对公表
            //合同表的写入
            array_walk($money, function (&$v, $k, $p) {
                $v = array_merge($v, $p);
            }, array('fin_co2buy_id' => $data['id']));
            $finids = $this->setfinco($money, $data['id']);
            Db::name('fin_co2buy_remarks')->where('fin_co2buy_id', $data['id'])->setField('remarks', $data['remarks']);//对公付款登记备注
            //公司流水
            $finupdata['update_id'] = session('userid');
            $finupdata['update_at'] = time();
            $fin_co_id =getValue('fin_co',['record_id'=>$data['id']],'id');//公司财务流水信息id
            $fin_ids = Db::name('fin_co')->where('id', $fin_co_id)->update($finupdata);//公司流水表
            Db::name('fin_co_remarks')->where('fin_co_id', $fin_co_id)->setField('remarks', $data['remarks']);//公司流水备注表
            if ($cotwoedit !== false && $finids && $fin_ids !== false) {
                Db::commit();
                return array('msg' => lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //删除合同表重新写入
    protected function setfinco($money, $fo_id)
    {
        //删除合同支付表
        Db::name('fin_co2buy_po')->where('fin_co2buy_id', $fo_id)->delete();
        $id = Db::name('fin_co2buy_po')->insertAll($money);
        return $id;
    }

    //付款登记的编辑显示接口
    public function cotwobuyedit($data)
    {
        $admin=session('admin');
        $admin_authids = explode(",", $admin['auth_ids']);//用户权限
        $info = $this->alias('a')->join('nt_fin_co2buy_remarks b', 'a.id=b.fin_co2buy_id', 'left')->field('a.*,b.remarks')->where('a.id', $data['id'])->find();
        $happentime=$info['happen_day'];//编辑的时间
        if ($data['lang'] != 'zh') {
            $info['happen_day'] = getTimeDate($info['happen_day'], 13);
        } else {
            $info['happen_day'] = getTimeDate($info['happen_day'], 7);
        }
        $wheremap['id'] = $info['co_id'];
        $wheremap['status'] = 'NORMAL';
        $info['companys'] =getables('company',$wheremap,'id,name');
        $success=array('status'=>1, 'msg'=>$info);//成功
        $fail=array('status'=>3, 'msg'=>lang("no_permission,_please_contact_administrator"));//没有权限
        if ($admin['position_id'] != 1 && $admin['position_id'] != 2) {
            if (in_array('399', $admin_authids)) {
                //拥有所有权限
                return $success;
            } elseif (in_array('397', $admin_authids) && !in_array('399', $admin_authids)) {
                //拥有7天权限
                $time = (time() -$happentime) / 86400;
                if (ceil($time) > 7) {
                    return $fail;
                } else {
                    return $success;
                }
            } elseif (in_array('184', $admin_authids) && !in_array('397', $admin_authids) && !in_array('399', $admin_authids)) {
                //拥有当天的权限
                $time = (time() - $happentime) / 86400;
                if (ceil($time) > 1) {
                    return $fail;
                } else {
                    return $success;
                }
            } else {
                //没有权限
                return $fail;
            }
        } else {
            return $success;
        }
    }
    //付款登记的详情查看
    public function cotwobuydetail($data)
    {
        $lang = $data['lang'];
        $info = $this->alias('a')->join('nt_fin_co2buy_remarks b', 'a.id=b.fin_co2buy_id', 'left')->field('a.*,b.remarks')->where('a.id', $data['id'])->find();
        //付款时间
        if ($lang != 'zh') {
            $info['happen_date'] = getTimeDate($info['happen_day'], 8);
        } else {
            $info['happen_date'] = getTimeDate($info['happen_day'], 7);
        }
        //通过对公付款id看付款了那几个合同
        $datapro = Db::name('fin_co2buy_po')->field('po_id')->where('fin_co2buy_id', $data['id'])->group('po_id')->select();
        //计算相关的数据
        foreach ($datapro as $dataprokey => $dataproval) {
            //获取合同的信息
            $infobuy = Db::name('buy_po')->field('delivery_day,paid_sum,cost_sum,price_sum')->where('id', $dataproval['po_id'])->find();//合同的信息

            //对公付款每一个合同的付款总数
            $infofins = Db::name('fin_co2buy_po')->field('sum(amount) as amount')->where(['fin_co2buy_id' => $data['id'], 'po_id' => $dataproval['po_id']])->find();
            //应付金额
            $moneyzhifu = $datapro[$dataprokey]['zhifu'] = $infobuy['cost_sum'] + $infobuy['price_sum'] - $infobuy['paid_sum'] + $infofins['amount'];
            //差额
            $cha = $moneyzhifu - $infofins['amount'];
            if ($cha <= 0) {
                $datapro[$dataprokey]['chahe'] = '-';
            } else {
                $datapro[$dataprokey]['chahe'] = $cha;
            }
            //支付金额
            $datapro[$dataprokey]['amount'] = $infofins['amount'];
            //付款日期
            $datapro[$dataprokey]['happen_date'] = $info['happen_date'];
            //交货日期
            if ($lang != 'zh') {
                $datapro[$dataprokey]['delivery_date'] = getTimeDate($infobuy['delivery_day'], 8);
            } else {
                $datapro[$dataprokey]['delivery_date'] = getTimeDate($infobuy['delivery_day'], 7);
            }
        }
        //支付账号(自己公司)
        $join = [
            ['nt_banks b', 'a.banks_id=b.id', 'left']
        ];
        //公司账号
        $infoone = getSearch('accounts', 'a', 'a.account_num,b.name', ['a.id' => $info['account_id']], $join, null)[0];
        $info['account_num'] = $infoone['account_num'];
        $info['bankname'] = $infoone['name'];

        //客户公司收款账号
        $infotwo = getSearch('co_bank', 'a', 'a.account_num,b.name', ['a.id' => $info['bank_id']], $join, null)[0];
        $info['companyaccount_num'] = $infotwo['account_num'];
        $info['companybankname'] = $infotwo['name'];
        //编辑者
        $info['updatename'] = getinfo($info['update_id'], 'admin')['nickname'];
        //供应商
        $info['companyname'] = getinfo($info['co_id'], 'company')['name'];
        return array('topdata' => $info, 'data' => $datapro);
    }

    //付款登记的伪删除
    public function cotwobuydel($data)
    {
        Db::startTrans();
        if ($data['code'] == 1) {
            //假删除
            $update['del_id'] = session('userid');
            $update['del_at'] = time();
            $cotwoid = $this->where('id', $data['id'])->update($update);
            $fin_ids = $buyid = $pro_id = 1;
        } else {
            $buyid = model('Buy')->delBuyPoFin($data['id']);
            //真删除
            $cotwoid = $this->where('id', $data['id'])->delete();//流水表

            $remarkid = Db::name('fin_co2buy_remarks')->where('fin_co2buy_id', $data['id'])->delete();//备注表

            $pro_id = Db::name('fin_co2buy_po')->where('fin_co2buy_id', $data['id'])->delete();//合同号表

            $fin_id = Db::name('fin_co')->where('record_id', $data['id'])->value('id'); //公司流水表id

            //公司流水备注表
            Db::name('fin_co_remarks')->where('fin_co_id', $fin_id)->delete();
            $fin_ids = Db::name('fin_co')->where('id', $fin_id)->delete();
        }
        if ($cotwoid && $pro_id && $buyid && $fin_ids) {
            Db::commit();
            return array('msg' => lang("deleted_successfully"), 'status' => 1);
        } else {
            return array('msg' => lang("failed_to_delete"), 'status' => 0);
        }
    }
}